<template>
  <div class="app-container">
    <el-form ref="elForm" :disabled="$route.query.isInfo" :model="formData" :rules="rules" size="medium"
      label-width="130px">
      <h2 style="text-align: center">试验室人员上岗审核</h2>
      <h4 class="form-header h4">基本信息</h4>
      <el-row :gutter="15">
        <el-col :span="8">
          <el-form-item label="人员" prop="userId">
            <UserDialog placeholder="请选择人员" @change="changeExamined" v-model="formData.userId"></UserDialog>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="部门" prop="deptId">
            <el-input disabled v-model="formData.deptName" placeholder="请输入部门" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请时间" prop="applyTime">
            <el-date-picker v-model="formData.applyTime" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
              :style="{ width: '100%' }" placeholder="请选择申请时间" clearable></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="申请业务范围" prop="applyScope">
            <!-- <el-input v-model="formData.applyScope" placeholder="请输入申请业务范围" /> -->
            <el-row type="flex" :gutter="20">
              <el-col :span="24">
                <el-table ref="multipleTable" height="500" v-loading="loading" border :data="deptList"
                  highlight-current-row @current-change="changeCurrentUser" @select-all="selectAll"
                  row-key="applyWorkSettingId" :default-expand-all="isExpandAll"
                  :tree-props="{ children: 'applyWorkSettings', hasChildren: 'hasChildren' }">
                  <el-table-column prop="list" width="55" type="selection" :selectable="row => !row.disabled">
                    <template slot-scope="scope">
                      <!-- {{ scope.row.selected }} -->
                      <el-checkbox v-model="scope.row.selected" @change="onRowSelect(scope.row)"></el-checkbox>
                    </template>
                  </el-table-column>
                  <el-table-column prop="content" label="内容"></el-table-column>
                  <el-table-column prop="sort" label="排序"></el-table-column>
                  <el-table-column label="编码" prop="type" align="center">
                  </el-table-column>
                </el-table>

              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="公路/水运资格证书" prop="certTypeId1">
            <treeselect
              :limit="10"
              :limitText="(count) => `+${count}`"
              :disabled="$route.query.isInfo"
              multiple
              @select="select"
              value-consists-of="ALL"
              v-model="certTypeId1"
              :options="cretList1"
              :normalizer="normalizer"
              placeholder="选择资格证书"
            />
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="12">
          <el-form-item label="建设试验资格证书" prop="certTypeId2">
            <treeselect
              multiple
              :limit="10"
              :limitText="(count) => `+${count}`"
              :disabled="$route.query.isInfo"
              value-consists-of="ALL"
              v-model="certTypeId2"
              :options="cretList2"
              :normalizer="normalizer"
              placeholder="选择资格证书"
            />
          </el-form-item>
        </el-col> -->
      </el-row>
      <h4 class="form-header h4">附件信息</h4>
      <el-form-item label="" prop="oss">
        <FileUploadBase :isDelete="!$route.query.isInfo" v-model="formData.oss"></FileUploadBase>
      </el-form-item>
      <el-col :span="24">
        <el-form-item label-width="0" style="text-align: center; margin-top: 30px">
          <el-button v-if="!$route.query.isInfo" type="primary" @click="submitForm">提交</el-button>
          <el-button v-if="!($route.query.isInfo || isInfo)" type="primary" @click="submitForm(0)">暂存</el-button>
          <el-button :disabled="false" @click="resetForm">返回</el-button>
        </el-form-item>
      </el-col>
    </el-form>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
// import { listCertType } from "@/api/system/qualification.js";

import { deptTreeSelect } from "@/api/system/user.js";
import { listSelect } from "@/api/device/device.js";
import businessDialogSelection from '@/components/businessDialogSelection/index'
import {
  applyWorkAdd,
  updategapplyWork,
  applyWorkInfo,
} from "@/api/device/applyWork.js";
import {
  listCertType,
} from "@/api/system/applyBusiness.js";
export default {
  components: { Treeselect, businessDialogSelection },
  props: [],
  data() {
    return {
      loading: false,
      formData: {
        userId: undefined,
        deptId: undefined,
        oss: undefined,
        contentList: undefined,
        applyScope: undefined,
        applyTime: null,
        scopes: []
      },
      // 是否展开，默认全部展开
      isExpandAll: true,
      deptOptions: [],
      rules: {
        oss: [
          {
            required: false,
            message: "附件不能为空",
            trigger: "change",
          },
        ],
        applyScope: [
          {
            required: true,
            message: "请输入申请业务范围",
            trigger: "blur",
          },
        ],
        applyTime: [
          {
            required: true,
            message: "请选择申请时间",
            trigger: "blur",
          },
        ],
        deptId: [
          {
            required: true,
            message: "请选择部门人员",
            trigger: "blur",
          },
        ],
        userId: [
          {
            required: true,
            message: "请输入人员",
            trigger: "change",
          },
        ],
      },
      userMultipleSelection: [],
      deviceOptions: [],
      cretList1: [],
      cretList2: [],
      cretListAll2: [],
      cretListAll1: [],

      certTypeId2: [],
      certTypeId1: [],
      flag: false,
      deptList: []
    };
  },
  computed: {},
  created() {
    this.getList()
    // this.listSelect();
    if (this.$route.query.isEdit || this.$route.query.isInfo) {
      this.getinfo();
    }
    this.getDeptTree();
    // this.getCretList(1);
    // this.getCretList(2);
  },
  mounted() { },
  methods: {
    /** 转换资格证书数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.certTypeId,
        label: node.certTypeName,
        children: node.children,
      };
    },
    /** 查询资格证书列表 */
    getList() {
      this.loading = true;
      // this.queryParams.type = this.type;
      listCertType().then((response) => {
        this.deptList = this.handleTree(response.data, "applyWorkSettingId");
        console.log(this.deptList);
        // this.deptList.forEach(item=>{
        //   item.selected = false
        // })
        this.loading = false;
      });
    },
    // 多选框选中数据
    selectAll(selection) {
      this.flag = !this.flag
      this.splite(this.deptList, this.flag)
    },
    changeCurrentUser(val) {
      console.log(val);
      this.currentUserId = val.userId;
    },
    splite(data, flag) {

      data.forEach((row) => {
        this.$refs.multipleTable.toggleRowSelection(row, flag);
        if (row.applyWorkSettings != null) {
          console.log(row.applyWorkSettings);
          this.splite(row.applyWorkSettings);
        }
      })
    },
    handleselectionChange(e) {
      console.log(e);
    },
    onRowSelect(row) {
      console.log(row, 'row.selected');
      this.formData.applyScope = JSON.stringify(row)
      // this.formData.scopes.push(row)
      // this.formData.contentList = row
      console.log(this.formData.contentList, 'undefined');

      if (row.applyWorkSettings && row.applyWorkSettings.length > 0) {
        this.traverse(row.applyWorkSettings, row.selected)
      }
    },
    traverse(data, checked) {
      data.forEach((row) => {
        this.$set(row, 'selected', checked)
        this.$forceUpdate()
        if (row.applyWorkSettings && row.applyWorkSettings.length > 0) {
          console.log(row.applyWorkSettings,'row.applyWorkSettings');
          this.traverse(row.applyWorkSettings, true);
        }
      })
      console.log(data, '...');
      console.log(this.deptList);
    },
    // getCretList(type) {
    //   listCertType({ type: type }).then((response) => {
    //     if (type == 1) {
    //       this.cretListAll1 = response.data;
    //       this.cretList1 = this.handleTree(response.data, "certTypeId");
    //     } else {
    //       this.cretListAll2 = response.data;

    //       this.cretList2 = this.handleTree(response.data, "certTypeId");
    //     }
    //   });
    // },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    changeExamined(e, i) {
      if (e) {
        this.formData.userName = e.nickName;
        this.formData.deptId = e.dept.deptId;
        this.formData.deptName = e.dept.deptName;
      } else {
        this.formData.userName = e.nickName;
        this.formData.deptId = undefined;
        this.formData.deptName = undefined;
      }
      console.log(this.formData);
    },
    listSelect() {
      listSelect().then((response) => {
        this.deviceOptions = response.data;
      });
    },
    getinfo() {
      applyWorkInfo(this.$route.query.id).then((response) => {
        // this.getList()
        this.formData = response.data;
        if (this.formData.contentList.length) {
          this.certTypeId1 = this.formData.contentList
            .filter((e) => e.type == 1)
            .map((e) => e.certTypeId);
          this.certTypeId2 = this.formData.contentList
            .filter((e) => e.type == 2)
            .map((e) => e.certTypeId);
        }
        // this.$set(this.formData,'applyScope',JSON.parse(this.formData.applyScope))
        // this.$forceUpdate()
        this.formData.applyScope = JSON.parse(this.formData.applyScope)
        console.log(this.formData.applyScope, 'applyScope');
        this.deptList.forEach((item) => {
          if (item.applyWorkSettingId == this.formData.applyScope.applyWorkSettingId) {
            console.log(item.applyWorkSettings, 'applyWorkSettings');
            this.$set(item, 'selected', true)
            console.log(item);
            // item.selected = true
            this.traverse(item.applyWorkSettings, true);
          }
        })

      });
    },
    submitForm(e) {
      let query = JSON.parse(JSON.stringify(this.formData));
      // if (this.certTypeId1.length) {
      query.contentList = this.cretListAll1
        .filter((e) => this.certTypeId1.includes(e.certTypeId))
        .map((i) => {
          return {
            certTypeId: i.certTypeId,
            code: i.code,
            certTypeName: i.certTypeName,
            type: i.type,
          };
        });
      // }
      // if (this.certTypeId2.length) {
      query.contentList.push(
        ...this.cretListAll2
          .filter((e) => this.certTypeId2.includes(e.certTypeId))
          .map((i) => {
            return {
              certTypeId: i.certTypeId,
              code: i.code,
              certTypeName: i.certTypeName,
              type: i.type,
            };
          })
      );
      // }
      console.log(query.contentList);
      // if (!query.contentList.length) {
      //   this.$message.warning("选择证书");
      //   return;
      // }
      if (query.status != 'end') {
        query.status = e == 0 ? 'draft' : 'audit'
      }

      if (e == 0) {
        // if (!this.formData.userId) {
        //   this.$message.warning("请先选择设备名称");
        //   return;
        // }
        if (this.formData.applyWorkId != undefined) {
          query.applyScope = JSON.stringify(this.formData.applyScope)
          updategapplyWork(query).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.resetForm();
          });
        } else {
          applyWorkAdd(query).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.resetForm();
          });
        }
        return
      }
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          console.log(this.contentList);
          if (this.formData.applyWorkId != undefined) {
            query.applyScope = JSON.stringify(this.formData.applyScope)
            updategapplyWork(query).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.resetForm();
            });
          } else {
            applyWorkAdd(query).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.resetForm();
            });
          }
        }
      });
    },
    select(e) {
      console.log(e);
    },
    resetForm() {
      const obj = { path: "./applyWork" };
      this.$tab.closeOpenPage(obj);
    },
  },
};
</script>
